<template>
  <div class="appointment">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>预约挂号</span>
        </div>
      </template>
      
      <el-steps :active="active" finish-status="success" simple>
        <el-step title="选择科室" />
        <el-step title="选择医生" />
        <el-step title="选择时间" />
        <el-step title="确认信息" />
      </el-steps>
      
      <!-- 步骤1：选择科室 -->
      <div v-if="active === 0" class="step-content">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(dept, index) in departments" :key="index">
            <el-card class="dept-card" shadow="hover" :class="{ 'selected': selectedDept === dept.id }" @click="selectDept(dept.id)">
              <div class="dept-icon">
                <el-icon :size="30"><component :is="dept.icon" /></el-icon>
              </div>
              <div class="dept-name">{{ dept.name }}</div>
              <div class="dept-desc">{{ dept.desc }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 步骤2：选择医生 -->
      <div v-if="active === 1" class="step-content">
        <el-row :gutter="20">
          <el-col :span="8" v-for="(doctor, index) in doctors" :key="index">
            <el-card class="doctor-card" shadow="hover" :class="{ 'selected': selectedDoctor === doctor.id }" @click="selectDoctor(doctor.id)">
              <div class="doctor-avatar">
                <el-avatar :size="80" :src="doctor.avatar"></el-avatar>
              </div>
              <div class="doctor-name">{{ doctor.name }}</div>
              <div class="doctor-title">{{ doctor.title }}</div>
              <div class="doctor-specialty">擅长：{{ doctor.specialty }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 步骤3：选择时间 -->
      <div v-if="active === 2" class="step-content">
        <el-row>
          <el-col :span="12">
            <el-calendar v-model="selectedDate">
              <template #dateCell="{ data }">
                <div class="date-cell" :class="{ 'available': isDateAvailable(data.day) }">
                  <p>{{ data.day.split('-').slice(2).join('-') }}</p>
                  <p v-if="isDateAvailable(data.day)" class="available-text">可预约</p>
                </div>
              </template>
            </el-calendar>
          </el-col>
          <el-col :span="12">
            <div class="time-slots">
              <h3>可预约时段</h3>
              <el-radio-group v-model="selectedTimeSlot">
                <el-radio v-for="(slot, index) in timeSlots" :key="index" :label="slot.id">
                  {{ slot.time }}
                </el-radio>
              </el-radio-group>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 步骤4：确认信息 -->
      <div v-if="active === 3" class="step-content">
        <el-descriptions title="预约信息确认" :column="1" border>
          <el-descriptions-item label="科室">{{ getDeptName(selectedDept) }}</el-descriptions-item>
          <el-descriptions-item label="医生">{{ getDoctorName(selectedDoctor) }}</el-descriptions-item>
          <el-descriptions-item label="日期">{{ formatDate(selectedDate) }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ getTimeSlot(selectedTimeSlot) }}</el-descriptions-item>
          <el-descriptions-item label="就诊人">
            <el-select v-model="selectedPatient" placeholder="请选择就诊人">
              <el-option v-for="patient in patients" :key="patient.id" :label="patient.name" :value="patient.id" />
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            <el-input v-model="remark" type="textarea" rows="3" placeholder="请输入备注信息" />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div class="step-actions">
        <el-button v-if="active > 0" @click="prev">上一步</el-button>
        <el-button v-if="active < 3" type="primary" @click="next">下一步</el-button>
        <el-button v-if="active === 3" type="success" @click="submitAppointment">提交预约</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { listDepartment } from '@/api/department'
import { listDoctor, getDoctor } from '@/api/doctor'
import { listTimeslot, addTimeslot } from '@/api/timeslot'

const active = ref(0)
const selectedDept = ref('')
const selectedDoctor = ref('')
const selectedDate = ref(new Date())
const selectedTimeSlot = ref('')
const selectedPatient = ref('')
const remark = ref('')

const loading = reactive({
  departments: false,
  doctors: false,
  timeSlots: false
})

const departments = ref([])
const doctors = ref([])
const timeSlots = ref([])

const patients = reactive([
  { id: 'patient1', name: '本人' },
  { id: 'patient2', name: '张三（父）' },
  { id: 'patient3', name: '李四（母）' }
])

// 加载科室数据
const fetchDepartments = () => {
  loading.departments = true
  
  listDepartment()
    .then(res => {
      if (res.code === 200) {
        departments.value = res.data || []
        
        // 如果没有数据，添加默认数据
        if (departments.value.length === 0) {
          departments.value = [
            {
              id: 'dept1',
              name: '内科',
              icon: 'Stethoscope',
              desc: '处理内脏疾病，如心脏、肺、胃肠等'
            },
            {
              id: 'dept2',
              name: '外科',
              icon: 'Operation',
              desc: '处理需要手术的疾病和损伤'
            },
            {
              id: 'dept3',
              name: '儿科',
              icon: 'FirstAidKit',
              desc: '专门处理儿童疾病和健康问题'
            }
          ]
        }
      } else {
        ElMessage.error(res.msg || '获取科室列表失败')
      }
    })
    .catch(error => {
      console.error('获取科室列表失败', error)
      // 添加默认数据
      departments.value = [
        {
          id: 'dept1',
          name: '内科',
          icon: 'Stethoscope',
          desc: '处理内脏疾病，如心脏、肺、胃肠等'
        },
        {
          id: 'dept2',
          name: '外科',
          icon: 'Operation',
          desc: '处理需要手术的疾病和损伤'
        },
        {
          id: 'dept3',
          name: '儿科',
          icon: 'FirstAidKit',
          desc: '专门处理儿童疾病和健康问题'
        }
      ]
    })
    .finally(() => {
      loading.departments = false
    })
}

// 加载医生数据
const fetchDoctors = (deptId) => {
  loading.doctors = true
  doctors.value = []
  
  const params = { departmentId: deptId }
  
  listDoctor(params)
    .then(res => {
      if (res.code === 200) {
        doctors.value = res.data || []
        
        // 如果没有数据，添加默认数据
        if (doctors.value.length === 0) {
          doctors.value = [
            {
              id: 'doc1',
              name: '张医生',
              title: '主任医师',
              specialty: '心血管疾病',
              avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
            },
            {
              id: 'doc2',
              name: '李医生',
              title: '副主任医师',
              specialty: '消化系统疾病',
              avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
            },
            {
              id: 'doc3',
              name: '王医生',
              title: '主治医师',
              specialty: '呼吸系统疾病',
              avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
            }
          ]
        }
      } else {
        ElMessage.error(res.msg || '获取医生列表失败')
      }
    })
    .catch(error => {
      console.error('获取医生列表失败', error)
      // 添加默认数据
      doctors.value = [
        {
          id: 'doc1',
          name: '张医生',
          title: '主任医师',
          specialty: '心血管疾病',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        {
          id: 'doc2',
          name: '李医生',
          title: '副主任医师',
          specialty: '消化系统疾病',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        {
          id: 'doc3',
          name: '王医生',
          title: '主治医师',
          specialty: '呼吸系统疾病',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        }
      ]
    })
    .finally(() => {
      loading.doctors = false
    })
}

// 加载时间段数据
const fetchTimeSlots = (doctorId, date) => {
  loading.timeSlots = true
  timeSlots.value = []
  
  const formattedDate = formatDate(date)
  const params = { 
    doctorId: doctorId,
    appointmentDate: formattedDate
  }
  
  listTimeslot(params)
    .then(res => {
      if (res.code === 200) {
        timeSlots.value = res.data || []
        
        // 如果没有数据，添加默认数据
        if (timeSlots.value.length === 0) {
          timeSlots.value = [
            { id: 'slot1', time: '上午 8:00-9:00' },
            { id: 'slot2', time: '上午 9:00-10:00' },
            { id: 'slot3', time: '上午 10:00-11:00' },
            { id: 'slot4', time: '下午 14:00-15:00' },
            { id: 'slot5', time: '下午 15:00-16:00' }
          ]
        }
      } else {
        ElMessage.error(res.msg || '获取预约时段失败')
      }
    })
    .catch(error => {
      console.error('获取预约时段失败', error)
      // 添加默认数据
      timeSlots.value = [
        { id: 'slot1', time: '上午 8:00-9:00' },
        { id: 'slot2', time: '上午 9:00-10:00' },
        { id: 'slot3', time: '上午 10:00-11:00' },
        { id: 'slot4', time: '下午 14:00-15:00' },
        { id: 'slot5', time: '下午 15:00-16:00' }
      ]
    })
    .finally(() => {
      loading.timeSlots = false
    })
}

// 监听选择的科室变化
watch(selectedDept, (newDeptId) => {
  if (newDeptId) {
    selectedDoctor.value = ''
    selectedTimeSlot.value = ''
    fetchDoctors(newDeptId)
  }
})

// 监听选择的日期变化
watch([selectedDoctor, selectedDate], ([newDoctorId, newDate]) => {
  if (newDoctorId && newDate) {
    selectedTimeSlot.value = ''
    fetchTimeSlots(newDoctorId, newDate)
  }
})

onMounted(() => {
  fetchDepartments()
})

const next = () => {
  if (active.value === 0 && !selectedDept.value) {
    ElMessage.warning('请选择科室')
    return
  }
  
  if (active.value === 1 && !selectedDoctor.value) {
    ElMessage.warning('请选择医生')
    return
  }
  
  if (active.value === 2 && !selectedTimeSlot.value) {
    ElMessage.warning('请选择预约时段')
    return
  }
  
  active.value++
}

const prev = () => {
  active.value--
}

const selectDept = (deptId) => {
  selectedDept.value = deptId
}

const selectDoctor = (doctorId) => {
  selectedDoctor.value = doctorId
}

const isDateAvailable = (date) => {
  const d = new Date(date)
  const today = new Date()
  
  // 过去的日期不可预约
  if (d < new Date(today.setHours(0, 0, 0, 0))) {
    return false
  }
  
  // 假设周末不可预约
  return d.getDay() !== 0 && d.getDay() !== 6
}

const getDeptName = (deptId) => {
  const dept = departments.value.find(d => d.id === deptId)
  return dept ? dept.name : ''
}

const getDoctorName = (doctorId) => {
  const doctor = doctors.value.find(d => d.id === doctorId)
  return doctor ? doctor.name : ''
}

const getTimeSlot = (slotId) => {
  const slot = timeSlots.value.find(s => s.id === slotId)
  return slot ? slot.time : ''
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const submitAppointment = () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请选择就诊人')
    return
  }
  
  // 构建预约数据
  const appointmentData = {
    departmentId: selectedDept.value,
    doctorId: selectedDoctor.value,
    patientId: selectedPatient.value,
    appointmentDate: formatDate(selectedDate.value),
    timeSlotId: selectedTimeSlot.value,
    remark: remark.value
  }
  
  // 提交预约
  addTimeslot(appointmentData)
    .then(res => {
      if (res.code === 200) {
        ElMessage.success('预约成功！请按时前往医院就诊')
        // 重置表单
        active.value = 0
        selectedDept.value = ''
        selectedDoctor.value = ''
        selectedDate.value = new Date()
        selectedTimeSlot.value = ''
        selectedPatient.value = ''
        remark.value = ''
      } else {
        ElMessage.error(res.msg || '预约失败')
      }
    })
    .catch(error => {
      console.error('预约失败', error)
      ElMessage.error('预约失败，请稍后再试')
    })
}
</script>

<style scoped>
.appointment {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.step-content {
  margin-top: 30px;
  margin-bottom: 30px;
}

.step-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dept-card, .doctor-card {
  height: 180px;
  margin-bottom: 20px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.dept-card.selected, .doctor-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

.dept-icon, .doctor-avatar {
  margin-bottom: 15px;
}

.dept-name, .doctor-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.dept-desc, .doctor-title, .doctor-specialty {
  color: #606266;
  text-align: center;
}

.date-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.available {
  color: #67c23a;
  font-weight: bold;
}

.available-text {
  font-size: 12px;
  margin-top: 5px;
}

.time-slots {
  padding: 20px;
}

.el-radio-group {
  display: flex;
  flex-direction: column;
}

.el-radio {
  margin-top: 15px;
}
</style>